package com.myMinistry.gui;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.myMinistry.Helper;
import com.myMinistry.R;
import com.myMinistry.provider.MinistryService;

public class Summary extends FragmentActivity {
	public static final String MY_PREFS = "defaults";
	public static final String MY_PREFS_KEY_CREATED = "created";
	public static final String MY_PREFS_KEY_PUBLISHER_ID = "publisherID";
	public static final String MY_PREFS_KEY_PUBLISHER_NAME = "publisherName";
	public static final String MY_PREFS_KEY_MULTI_PUBLISHERS = "multiplePublishers";
	public static final String VERSION_KEY = "version_number";
	
	private final Calendar monthPicked = Calendar.getInstance();
	private final Calendar startDate = Calendar.getInstance();
	private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	private final SimpleDateFormat dateMonthAndYearFormat = new SimpleDateFormat("MMMM yyyy");
	public TextView header, v_totalHours, books, brochures, magazines, returnVisits, studies, rbc;
	private int publisherID = 0;
	private MinistryService database;
	private boolean monthView = true;
	
	private SharedPreferences sharedPref;
	
	SimpleCursorAdapter mAdapter;
	
	@Override
	public void onStop() {
		super.onStop();
		database.close();
    }
	
	@Override
	public void onStart() {
		super.onStart();
		/** Get variables to do a check to see if we should display the "What's New" section. */
		int currentVersionNumber = 0;
		int savedVersionNumber = sharedPref.getInt(VERSION_KEY, 0);
		
		try {
			PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
			currentVersionNumber = pi.versionCode;
		} catch (Exception e) {}
		
		/** If we should show the dialog then show it, then save that they have seen it so we don't show them this again on the same code version. */
		if (currentVersionNumber > savedVersionNumber) {
			showWhatsNewDialog();
			Editor editor = sharedPref.edit();
			editor.putInt(VERSION_KEY, currentVersionNumber);
			editor.commit();
		}
		
		publisherID = sharedPref.getInt(Summary.MY_PREFS_KEY_PUBLISHER_ID, 0);
		
		if(monthView)
			fillMonthData();
		else
			fillYearData();
    }
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	Bundle extras = getIntent().getExtras();
    	setContentView(R.layout.summary);
    	
    	database = new MinistryService(this);
    	
    	/** Set the touch listener to be able to change data based on how the user swipes the screen. */
    	ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector();
    	findViewById(R.id.scrollView).setOnTouchListener(activitySwipeDetector);
    	
    	if(extras != null) {
	    	Object[] keys = extras.keySet().toArray();
	    	
	    	for(int i = 0; i < keys.length; i++) {
	    		if(keys[i].toString().equals("month"))
	    			monthPicked.set(Calendar.MONTH, extras.getInt("month"));
	    		else if(keys[i].toString().equals("year"))
	    			monthPicked.set(Calendar.YEAR, extras.getInt("year"));
	    	}
    	}
    	
    	books = (TextView) findViewById(R.id.books);
    	brochures = (TextView) findViewById(R.id.brochures);
    	magazines = (TextView) findViewById(R.id.magazines);
    	rbc = (TextView) findViewById(R.id.rbc);
    	returnVisits = (TextView) findViewById(R.id.returnVisits);
    	studies = (TextView) findViewById(R.id.studies);
    	header = (TextView) findViewById(R.id.header);
    	v_totalHours = (TextView) findViewById(R.id.totalHours);
    	
    	sharedPref = getSharedPreferences(Summary.MY_PREFS, Context.MODE_PRIVATE);
    	
    	findViewById(R.id.add_time).setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				database.close();
				Intent intent = new Intent(getApplicationContext(), TimeEditor.class);
				startActivity(intent);
				finish();
			}
		});
    }
	
    public void fillMonthData() {
    	database.openWritable();
    	String formattedDate = dateFormat.format(monthPicked.getTime()).toString();
    	double rbcHours = database.fetchRBCHoursForMonthForPublisher(formattedDate, publisherID);
    	
    	header.setText(new StringBuilder().append(getApplicationContext().getString(R.string.summaryFor)).append(" ").append(dateMonthAndYearFormat.format(monthPicked.getTime())));
    	v_totalHours.setText(Helper.numberFormatNoFloat(database.fetchHoursForMonthForPublisher(formattedDate, publisherID)));
    	books.setText(String.valueOf(database.fetchBooksPlacedCountForPublisher(formattedDate, "month", publisherID)));
    	brochures.setText(String.valueOf(database.fetchBrochuresPlacedCountForPublisher(formattedDate, "month", publisherID)));
    	magazines.setText(String.valueOf(database.fetchMagazinesPlacedCountForPublisher(formattedDate, "month", publisherID)));
    	returnVisits.setText(String.valueOf(database.fetchReturnVisitCountForPublisher(formattedDate, "month", publisherID)));
    	studies.setText(String.valueOf(database.fetchStudyCountForPublisher(formattedDate, "month", publisherID)));
    	
    	if(rbcHours > 1) {
    		rbc.setVisibility(View.VISIBLE);
    		rbc.setText(getApplicationContext().getString(R.string.rbcHours) + ": " + Helper.numberFormat(rbcHours));
    	}
    	else {
    		rbc.setVisibility(View.GONE);
    	}
    	database.close();
    }
	
    private void fillYearData() {
    	database.openWritable();
    	if(startDate.get(Calendar.MONTH) < 9)
    		startDate.set(startDate.get(Calendar.YEAR) - 1, 9, 1);
    	else
    		startDate.set(startDate.get(Calendar.YEAR), 9, 1);
    	
    	String formattedDate = dateFormat.format(startDate.getTime()).toString();
    	double rbcHours = database.fetchRBCHoursForYearForPublisher(formattedDate, publisherID);
    	
    	header.setText(new StringBuilder().append(getApplicationContext().getString(R.string.serviceYearSummaryFor)).append(" ").append(startDate.get(Calendar.YEAR)));
    	v_totalHours.setText(Helper.numberFormatNoFloat(database.fetchHoursForYearForPublisher(formattedDate, publisherID)));
    	books.setText(String.valueOf(database.fetchBooksPlacedCountForPublisher(formattedDate, "year", publisherID)));
    	brochures.setText(String.valueOf(database.fetchBrochuresPlacedCountForPublisher(formattedDate, "year", publisherID)));
    	magazines.setText(String.valueOf(database.fetchMagazinesPlacedCountForPublisher(formattedDate, "year", publisherID)));
    	returnVisits.setText(String.valueOf(database.fetchReturnVisitCountForPublisher(formattedDate, "year", publisherID)));
    	studies.setText(String.valueOf(database.fetchStudyCountForPublisher(formattedDate, "year", publisherID)));
    	
    	if(rbcHours > 1) {
    		rbc.setVisibility(View.VISIBLE);
    		rbc.setText(getApplicationContext().getString(R.string.rbcHours) + ": " + Helper.numberFormat(rbcHours));
    	}
    	else {
    		rbc.setVisibility(View.GONE);
    	}
    	database.close();
    }
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu){
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.summary_month, menu);
    	return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
	        case R.id.manageHouseholders:
	        	startActivity(new Intent(getApplicationContext(), Householders.class));
	        	return true;
	        case R.id.manageLiterature:
	        	startActivity(new Intent(getApplicationContext(), LiteratureManager.class));
	        	return true;
	        case R.id.managePublishers:
	        	startActivity(new Intent(getApplicationContext(), Publishers.class));
	        	finish();
	        	return true;
	        case R.id.preferences:
	        	startActivity(new Intent(getApplicationContext(), Preferences.class));
	        	return true;
	        default:
	        	return super.onOptionsItemSelected(item);
    	}
    }
    
    private void showWhatsNewDialog() {
    	LayoutInflater inflater = LayoutInflater.from(this);
    	View view = inflater.inflate(R.layout.dialog_whatsnew, null);
    	Builder builder = new AlertDialog.Builder(this);
    	builder.setIcon(R.drawable.launcher_icon);
    	builder.setView(view).setTitle(R.string.whatsNew)
		.setPositiveButton(R.string.nowIKnow, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
    	builder.create().show();
    }
	
	public class ActivitySwipeDetector implements View.OnTouchListener {
		static final int MIN_DISTANCE = 100;
		private float downX, upX, downY, upY;
		
		public ActivitySwipeDetector(){ /* Empty */ }
		public void onTopToBottomSwipe() {
			monthView = !monthView;
			if(monthView)
				fillMonthData();
			else
				fillYearData();
		}
		public void onBottomToTopSwipe() {
			monthView = !monthView;
			if(monthView)
				fillMonthData();
			else
				fillYearData(); 
		}
		
		public void onRightToLeftSwipe(){
			if(monthView) {
				monthPicked.add(Calendar.MONTH, 1);
				fillMonthData();
			}
			else {
				startDate.add(Calendar.YEAR, 1);
				fillYearData();
			}
		}
		public void onLeftToRightSwipe(){
			if(monthView) {
				monthPicked.add(Calendar.MONTH, -1);
				fillMonthData();
			}
			else {
				startDate.add(Calendar.YEAR, -1);
				fillYearData();
			}
		}
		
		public boolean onTouch(View v, MotionEvent event) {
			try {
				if(event.getAction() == MotionEvent.ACTION_DOWN) {
					downX = event.getX();
					downY = event.getY();
				}
				else if(event.getAction() == MotionEvent.ACTION_UP) {
					upX = event.getX();
					upY = event.getY();
					float deltaX = downX - upX;
					float deltaY = downY - upY;
					/** swipe horizontal? */
					if(Math.abs(deltaX) > MIN_DISTANCE) {
						/** left or right */
						if(deltaX < 0) { this.onLeftToRightSwipe(); return true; }
						if(deltaX > 0) { this.onRightToLeftSwipe(); return true; }
					}
					
					/** swipe vertical? */
					else if(Math.abs(deltaY) > MIN_DISTANCE){
						/** top or down */
						if(deltaY < 0) { this.onTopToBottomSwipe(); return true; }
						if(deltaY > 0) { this.onBottomToTopSwipe(); return true; }
					}
				}
				
				return true;
			}
			catch(Exception e) {
				return true;
			}
		}
	}
	
	public void showDialog() {
		/** DialogFragment.show() will take care of adding the fragment
		 * in a transaction. We also want to remove any currently showing
		 * dialogs, so make our own transaction and take care of that here. */
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
		if(prev != null)
			ft.remove(prev);
		ft.addToBackStack(null);
		/** Create and show the dialog. */
		DialogFrag newFragment = DialogFrag.newInstance(getApplicationContext().getString(R.string.menuPublishers), DialogFrag.ACTIVE_PUBLISHERS);
		newFragment.show(getSupportFragmentManager(), "dialog");
	}
	
	public void createNewPublisherShowDialog() {
		/** DialogFragment.show() will take care of adding the fragment
		 * in a transaction. We also want to remove any currently showing
		 * dialogs, so make our own transaction and take care of that here. */
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
		if(prev != null)
			ft.remove(prev);
		ft.addToBackStack(null);
		/** Create and show the dialog. */
		DialogFrag newFragment = DialogFrag.newInstance(getApplicationContext().getString(R.string.publishersName), DialogFrag.CREATE_PUBLISHER);
		newFragment.show(getSupportFragmentManager(), "dialog");
	}
	
	public void updatePublisher(int newPublisherID, String publisherName) {
		/** Update display name from fragment */
		ActionBarFragment fragment = (ActionBarFragment)getSupportFragmentManager().findFragmentById(R.id.action_bar_fragment);
		fragment.setSelectedPublisherNameText(publisherName);
		
		/** Update local variable and update the summary info */
		publisherID = newPublisherID;
		if(monthView)
			fillMonthData();
		else
			fillYearData();
	}
	
	public void shareTime() {
		StringBuilder smsString = new StringBuilder();
		
		smsString.append(getApplicationContext().getString(R.string.totalHoursOneLine) + ": " + v_totalHours.getText());
		
		if(books.getText() != "0")
			smsString.append("\n" + getApplicationContext().getString(R.string.books) + ": " + books.getText());
		if(brochures.getText() != "0")
			smsString.append("\n" + getApplicationContext().getString(R.string.booklets) + ": " + brochures.getText());
		if(magazines.getText() != "0")
			smsString.append("\n" + getApplicationContext().getString(R.string.magazines) + ": " + magazines.getText());
		if(returnVisits.getText() != "0")
			smsString.append("\n" + getApplicationContext().getString(R.string.returnVisitsOneLine) + ": " + returnVisits.getText());
		if(studies.getText() != "0")
			smsString.append("\n" + getApplicationContext().getString(R.string.studies) + ": " + studies.getText());
		if(rbc.getVisibility() == View.VISIBLE && rbc.getText() != "0")
			smsString.append("\n" + getApplicationContext().getString(R.string.rbcHours) + ": " + rbc.getText());
		
		Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
		sharingIntent.setType("text/plain");
		sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, smsString.toString());
		startActivity(Intent.createChooser(sharingIntent, "Share via"));
	}
	
	public void viewEntries() {
		Intent intent = new Intent(getApplicationContext(), TimeEntries.class);
		intent.putExtra("month", monthPicked.get(Calendar.MONTH));
		intent.putExtra("year", monthPicked.get(Calendar.YEAR));
		intent.putExtra("monthView", monthView);
		startActivity(intent);
		finish();
	}
}